<template>
  <div style="width: 100%; padding: 0 0; position: relative">
    <div v-if="form.diagnoseNo" style="position: absolute; top: -40px; left: 100px">
      <el-alert
        v-if="tips == 0"
        :title="'门店还未做过复盘, 请填写完信息后点击【新建】'"
        type="warning"
        :closable="false"></el-alert>
      <el-alert
        v-if="tips == 1"
        :title="'查询出最近一次复盘填写的基础信息, 如果是重新做复盘, 请修改后点击【新建】'"
        type="success"
        :closable="false"></el-alert>
      <el-alert v-if="tips == 2" :title="'今天已做过复盘, 只能做【修改】'" type="success" :closable="false"></el-alert>
    </div>
    <el-form ref="form" :model="form" :rules="rules" label-width="200px" size="medium">
      <div class="diagnose_2_form">
        <div>
          <el-form-item label="门店名称" prop="salonName">
            <region-select ref="refSalonSelect" :mode="2" :dept="2" @selected="handleSalonSelected"></region-select>
          </el-form-item>
          <el-form-item v-if="form.id" label="复盘单编号" prop="diagnoseNo">
            <el-input v-model="form.diagnoseNo" disabled style="width: 330px"></el-input>
          </el-form-item>
          <el-form-item label="门店规模" prop="salonScale">
            <el-select v-model="form.salonScale" placeholder="--请选择--" clearable style="width: 330px">
              <el-option
                v-for="item in baseEnums['salonSize']"
                :key="item.code"
                :label="item.name"
                :value="item.code"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="门店属性" prop="salonAttribute">
            <el-select v-model="form.salonAttribute" placeholder="--请选择--" clearable style="width: 330px">
              <el-option
                v-for="item in baseEnums['salonAttr']"
                :key="item.code"
                :label="item.name"
                :value="item.code"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="门店类型" prop="salonType">
            <el-select v-model="form.salonType" placeholder="--请选择--" clearable style="width: 330px">
              <el-option
                v-for="item in baseEnums['salonType']"
                :key="item.code"
                :label="item.name"
                :value="item.code"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商圈环境" prop="businessEnvironment">
            <el-select v-model="form.businessEnvironment" placeholder="--请选择--" clearable style="width: 330px">
              <el-option
                v-for="item in baseEnums['businessEnvironment']"
                :key="item.code"
                :label="item.name"
                :value="item.code"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="上次装修时间" prop="lastDecorationTime">
            <el-date-picker
              v-model="form.lastDecorationTime"
              type="month"
              format="yyyy-MM"
              value-format="yyyy-MM"
              placeholder="选择日期"
              :picker-options="{ disabledDate: picDisabledDate }"></el-date-picker>
          </el-form-item>
          <el-form-item label="经营启动时间" prop="operationStartTime">
            <el-date-picker
              v-model="form.operationStartTime"
              type="month"
              format="yyyy-MM"
              value-format="yyyy-MM"
              placeholder="选择日期"
              :picker-options="{ disabledDate: picDisabledDate }"></el-date-picker>
          </el-form-item>
          <el-form-item label="主要竞争力自评(占70%)" prop="mainCompetition">
            <el-select v-model="form.mainCompetition" placeholder="--请选择--" clearable style="width: 330px">
              <el-option
                v-for="item in baseEnums['salonCompetitiveness']"
                :key="item.code"
                :label="item.name"
                :value="item.code"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="次要竞争力自评(占30%)" prop="subCompetition">
            <el-select v-model="form.subCompetition" placeholder="--请选择--" clearable style="width: 330px">
              <el-option
                v-for="item in baseEnums['salonCompetitiveness']"
                :key="item.code"
                :label="item.name"
                :value="item.code"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="主要缺陷自评(占70%)" prop="mainDefect">
            <el-select v-model="form.mainDefect" placeholder="--请选择--" clearable style="width: 330px">
              <el-option
                v-for="item in baseEnums['salonCompetitiveness']"
                :key="item.code"
                :label="item.name"
                :value="item.code"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="次要缺陷自评(占30%)" prop="subDefect">
            <el-select v-model="form.subDefect" placeholder="--请选择--" clearable style="width: 330px">
              <el-option
                v-for="item in baseEnums['salonCompetitiveness']"
                :key="item.code"
                :label="item.name"
                :value="item.code"></el-option>
            </el-select>
          </el-form-item>
        </div>
      </div>
      <el-form-item>
        <el-button type="primary" :disabled="tips == 2" @click="handleSubmitForm('form', true)">新建</el-button>
        <el-button v-if="form.id" type="warning" @click="handleSubmitForm('form', false)">修改</el-button>
        <el-button @click="resetForm('form')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import * as apiSts from '@/api/_com_';
// 引入后端 API
import { addBaseDiagnose, getBaseDiagnoseLast, getBaseEnums, updateBaseDiagnose } from '@/api/diagnose';
// 引入自定义组件
import '@/utils/datefmt';
import RegionSelect from '@/views/salon/RegionSelect.vue';
import { d2FlexibleHistory2Server, d2FlexibleHistory4Server } from './diagnose2';
// 引入第三方组件
import { MessageBox } from 'element-ui';
import { mapGetters } from 'vuex';

export default {
  name: 'Diagnose2',
  components: { ['region-select']: RegionSelect },
  data() {
    return {
      baseEnums: {},
      isFetching: false,
      salon: {},
      form: {
        id: undefined,
        salonId: '',
        salonNo: '',
        salonName: '',
        diagnoseNo: '',
        salonScale: '',
        salonAttribute: '',
        salonType: '',
        businessEnvironment: '',
        lastDecorationTime: '',
        operationStartTime: '',
        mainCompetition: '',
        subCompetition: '',
        mainDefect: '',
        subDefect: '',
      },
      rules: {
        salonScale: [{ required: true, message: '门店规模是必填项', trigger: 'blur' }],
        salonAttribute: [{ required: true, message: '门店属性是必填项', trigger: 'blur' }],
        salonType: [{ required: true, message: '门店类型是必填项', trigger: 'blur' }],
        businessEnvironment: [{ required: true, message: '商圈环境是必填项', trigger: 'blur' }],
        mainCompetition: [{ required: true, message: '主要竞争力自评是必填项', trigger: 'blur' }],
        subCompetition: [{ required: true, message: '次要竞争力自评是必填项', trigger: 'blur' }],
        mainDefect: [{ required: true, message: '主要缺陷自评是必填项', trigger: 'blur' }],
        subDefect: [{ required: true, message: '次要缺陷自评是必填项', trigger: 'blur' }],
      },
      tips: 0, // 提示信息类别: 0-没有创建过复盘单; 1-今天之前创建过复盘单; 2-今天创建过复盘单
    };
  },
  computed: {
    ...mapGetters(['deptId', 'openId']),
  },
  created() {
    this.loadBaseEnums();
  },
  mounted() {
    if (this.$refs.refSalonSelect && this.deptId == 15) {
      this.$refs.refSalonSelect.setSalonId(this.openId, true);
    }
  },
  methods: {
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.form.id = undefined;
    },
    picDisabledDate(date) {
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      return !(date - today < 0);
    },
    loadBaseEnums: async function () {
      const errAlertMsg = '查询类型失败';
      getBaseEnums()
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          const ret = res.data.data;
          if (ret) {
            this.baseEnums = Object.assign({}, ret);
          }
        })
        .catch(err => {
          console.log('loadBaseEnums', err);
          MessageBox.alert(errAlertMsg);
        });
    },
    loadBaseDiagnose: async function () {
      if (this.isFetching) {
        return;
      }
      if (!this.form.salonId) {
        return;
      }
      const sid = this.form.salonId;
      this.isFetching = true;
      this.resetForm('form');
      const errAlertMsg = '查询失败';
      getBaseDiagnoseLast(sid)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          const ret = res.data.data;
          if (ret) {
            d2FlexibleHistory4Server(ret);
            this.form = Object.assign({}, ret);
            this.form.salonId = ret.salonId + '';
            const dNoToday = new Date().format('yyMMdd'); // 按照业务规则, 门店一天只能创建一张复盘单
            if (ret.diagnoseNo.slice(-6) === dNoToday) {
              this.tips = 2;
            } else {
              this.tips = 1;
            }
            const eParam = {
              salonId: ret.salonId,
              salonNo: ret.salonNo,
              salonName: ret.salonName,
              diagnoseNo: ret.diagnoseNo,
              performPeriod: ret.performPeriod,
            };
            this.$emit('updated', eParam);
          } else {
            this.tips = 0;
            this.$emit('updated', undefined);
          }
        })
        .catch(err => {
          console.log('getBaseDiagnoseLast', err);
          MessageBox.alert(errAlertMsg);
        })
        .finally(() => {
          this.isFetching = false;
        });
    },
    handleSalonSelected: async function (salon) {
      if (salon) {
        this.form.salonId = salon.salonId;
        this.salon.salonNo = salon.salonCode;
        this.salon.salonName = salon.salonName;
        this.loadBaseDiagnose();
      }
    },
    handleSubmitForm: async function (formName, isadd) {
      let doSubmit = true;
      if (!isadd && this.form.diagnoseNo) {
        const diagnoseDay = this.form.diagnoseNo.slice(-6);
        const diagnoseToday = new Date().format('yyMMdd');
        if (diagnoseDay !== diagnoseToday) {
          await this.$confirm('当前复盘单不是今天创建的, 是否继续修改?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              doSubmit = true;
            })
            .catch(() => {
              doSubmit = false;
            });
        }
      }
      if (doSubmit) {
        await this.doSubmitForm(formName, isadd);
      }
    },
    doSubmitForm: async function (formName, isadd) {
      this.form.salonNo = this.salon.salonNo;
      this.form.salonName = this.salon.salonName;
      if (
        this.form.lastDecorationTime &&
        this.form.lastDecorationTime.format &&
        typeof this.form.lastDecorationTime.format === 'function'
      ) {
        this.form.lastDecorationTime = this.form.lastDecorationTime.format('yyyy-MM-dd HH:mm:ss');
      }
      if (
        this.form.operationStartTime &&
        this.form.operationStartTime.format &&
        typeof this.form.operationStartTime.format === 'function'
      ) {
        this.form.operationStartTime = this.form.operationStartTime.format('yyyy-MM-dd HH:mm:ss');
      }
      this.$refs[formName].validate(valid => {
        if (!valid) {
          console.log('error submit!!');
          return false;
        }
        if (isadd) {
          this.form.id = null;
          this.form.diagnoseNo = null;
        }
        const param = Object.assign({}, this.form);
        d2FlexibleHistory2Server(param);
        const callFunc = isadd ? addBaseDiagnose : updateBaseDiagnose;
        const errAlertMsg = isadd ? '创建失败' : '修改失败';
        callFunc(param)
          .then(res => {
            if (res.data.status !== apiSts.ResponseOK) {
              if (res.data.message) {
                MessageBox.alert(res.data.message);
              } else {
                MessageBox.alert(errAlertMsg);
              }
              return;
            }
            if (isadd) {
              this.loadBaseDiagnose();
            }
            MessageBox.alert(isadd ? '创建成功' : '修改成功');
          })
          .catch(err => {
            console.log('doSubmitForm', err);
            MessageBox.alert(errAlertMsg);
          });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.diagnose_2_form {
  width: 90%;
  display: flex;
  flex-direction: row;
  justify-content: space-evenly;
  gap: 50px;
}
.diagnose_2_form label {
  width: 90px;
  color: #99a9bf;
}
.diagnose_2_form .el-form-item {
  margin-right: 0;
  margin-bottom: 5px;
  width: 50%;
}
</style>
